Passed
Pull Request — master (#90)
by Mathieu
01:51
created

FileEncryptionAdapter.getEncryptionKey   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 1
1
import * as crypto from 'crypto';
2
import {Injectable} from '@nestjs/common';
3
import {ConfigService} from '@nestjs/config';
4
import {IFileEncryption} from 'src/Application/IFileEncryption';
5
6
@Injectable()
7
export class FileEncryptionAdapter implements IFileEncryption {
8
  constructor(private readonly configService: ConfigService) {}
9
10
  public async encrypt(buffer: Buffer): Promise<Buffer> {
11
    const iv = crypto.randomBytes(16);
12
    const key = await this.getEncryptionKey();
13
    const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
14
15
    return Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
16
  }
17
18
  public async decrypt(buffer: Buffer): Promise<Buffer> {
19
    const key = await this.getEncryptionKey();
20
    const iv = buffer.slice(0, 16);
21
    buffer = buffer.slice(16);
22
    const decipher = crypto.createDecipheriv('aes-256-ctr', key, iv);
23
24
    return Buffer.concat([decipher.update(buffer), decipher.final()]);
25
  }
26
27
  private async getEncryptionKey(): Promise<string> {
28
    const key = await this.configService.get<string>('FILE_ENCRYPTION_KEY');
29
30
    return crypto
31
      .createHash('sha256')
32
      .update(key)
33
      .digest('base64')
34
      .substr(0, 32);
35
  }
36
}
37